# logger/logger.py - 日志模块
import logging
import logging.handlers
import os
from pathlib import Path
from datetime import datetime

class AppLogger:
    """应用程序日志管理器"""
    
    def __init__(self, config, name="WebDAVNotes"):
        self.config = config
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)
        
        # 确保日志目录存在
        log_dir = config.base_dir / "logs"
        log_dir.mkdir(exist_ok=True)
        
        # 设置日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 文件处理器 - 按日期滚动
        log_file = log_dir / f"{name}.log"
        file_handler = logging.handlers.TimedRotatingFileHandler(
            log_file, when='midnight', interval=1, backupCount=7,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        
        # 控制台处理器 (可选，用于调试)
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        
        # 添加处理器到日志器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
    
    def debug(self, message, *args, **kwargs):
        """记录调试信息"""
        self.logger.debug(message, *args, **kwargs)
    
    def info(self, message, *args, **kwargs):
        """记录一般信息"""
        self.logger.info(message, *args, **kwargs)
    
    def warning(self, message, *args, **kwargs):
        """记录警告信息"""
        self.logger.warning(message, *args, **kwargs)
    
    def error(self, message, *args, **kwargs):
        """记录错误信息"""
        self.logger.error(message, *args, **kwargs)
    
    def exception(self, message, *args, **kwargs):
        """记录异常信息"""
        self.logger.exception(message, *args, **kwargs)
    
    def log_operation(self, operation: str, status: str, details: str = ""):
        """记录操作日志"""
        log_message = f"操作: {operation}, 状态: {status}"
        if details:
            log_message += f", 详情: {details}"
        self.info(log_message)

# 全局日志实例
_logger_instance = None

def get_logger(config=None, name="WebDAVNotes"):
    """获取日志实例"""
    global _logger_instance
    if _logger_instance is None and config is not None:
        _logger_instance = AppLogger(config, name)
    return _logger_instance

def set_logger(logger):
    """设置日志实例（用于测试）"""
    global _logger_instance
    _logger_instance = logger